define(function(require, exports, module){
	require("resource/js/easyui/easyloader.js");
	require("resource/font-awesome-4.7.0/css/font-awesome.min.css");
	var AJAX = require("resource/js/component/ajax.js");
	var createMenuItem = function(items,menu){
		if(items.length==0) return;
		$.each(items,function(i,item){
			item = $.fn.tree.defaults.setting.menu.defaults[item];
			if(!item) return;
			if(!item.parent)
				menu.menu("appendItem",item);
			else{
				var result = menu.menu('findItem', item.parent);
				if(result){
					item.parent = result.target;
					menu.menu("appendItem",item);
				}else{
					delete item.parent;
					menu.menu("appendItem",item);
				}
			}
		});
	}
	var initMenu = function(menu,opt){
		if(opt.setting.menu.enable){
			opt.divs.menu = menu;
			menu.appendTo(this);
			menu.menu({
				onClick:function(arg){
					opt.setting.menu.onClick.call(opt,arg,$.data(this).treenode);
				}
			});
			createMenuItem(opt.setting.menu.items,menu);
		}else{
			menu.remove();
		}
	}
	var initLoading = function(loading,opt){
		opt.divs.loadding = loading;
		loading.appendTo(this);
	}
	var initZtree = function(ztree,opt){
		opt.divs.ztree = ztree;
		ztree.appendTo(this);
	}
	var nodeList = [];
	var searchNode = function(key,opt){
		var zTree = $.fn.zTree.getZTreeObj(opt.treeid);
		if(opt.searchtype=="hightlight"){
			zTree.expandAll(false);
			zTree.refresh();
			var value = $.trim(key);
			updateNodes(false);
			if(value==""){
				return [];
			}else{
				nodeList = zTree.getNodesByParamFuzzy("name", value);
				updateNodes(true);
			}
			return nodeList;
			function updateNodes(highlight) {
				for( var i=0, l=nodeList.length; i<l; i++) {
					nodeList[i].highlight=highlight;
					zTree.updateNode(nodeList[i]);
					if(!!highlight){
						expandNode(nodeList[i]);
					}
				}
			}
			function expandNode(e) {
				if(!e.isParent){
					e = zTree.getNodesByParam("id",e.pId,null)[0];
				}
				zTree.expandNode(e, true, null, null, null);
			}
		}else{
			zTree.showNodes(zTree.getNodesByParam("isHidden", true));
			var value = $.trim(key);
			if(value==""){
				return [];
			}else{
				nodes = zTree.getNodesByFilter(function(node){
					node.isHidden = true;
					if(node.locked==true||node.name.indexOf(value)!=-1){
						node.isHidden = false;
					}
					return node.isHidden;
				});
				var nps = [];
				var grepNode = function(node){
					if(node.children){
						for(var i=0;i<node.children.length;i++){
							if(!grepNode(node.children[i]).isHidden){
								nps.push(node);
								node.isHidden = false;
								break;
							}
						}
					}
					return node;
				}
				var node ,ns=[];
				for(var ni = 0;ni<nodes.length;ni++){
					node = grepNode(nodes[ni]);
					if(node.isHidden) ns.push(node);
				}
				for(var ni in nps){
					zTree.expandNode(nps[ni], true, null, null, null);
				}
				zTree.hideNodes(ns);
			}
			return nodeList;
		}
	}
	var initSerchbox = function(searchbox,opt){
		if(opt.searchable){
			opt.divs.searchbox = searchbox;
			searchbox.appendTo(this);
			opt.searchopt.onClickIcon=function(val){
				searchNode($(this).val(),opt);
			};
			searchbox.textbox(opt.searchopt);
			searchbox.textbox("textbox").css("max-height","34px");
		}else{
			searchbox.remove();
		}
	}
	var load = function(opt,upfun){
		var checks = "";
		if(typeof opt.checks == "string"){
			checks = opt.checks;
		}else{
			var rows = opt.checks;
			for(var key=rows.length-1;key>=0;key--){
				if(key==0){
					if(rows[key])
						checks += rows[key];
				}else{
					if(rows[key]){
						checks += rows[key]+",";
					}
				}
			}
		}
		var jq = this;
		using(["ztree"],function(){
			$.fn.zTree._z.data.addZTreeTools(
					function(setting, tool) {
						tool.showMenu = function(arg,treeNode){
							if(opt.setting.menu.enable){
								setting.menu.onShow.call(jq,treeNode);
								opt.divs.menu.menu("show",arg);
								$.data(opt.divs.menu[0],"treenode",treeNode);
							}
						}
					});
			opt.divs.loadding.show();
			var tree = null;
			if(opt.url!=null&&$.trim(opt.url)!=''){
				AJAX.init().success(function(code,msg,data){
					tree = $.fn.zTree.init(opt.divs.ztree, opt.setting, data);
					opt.divs.loadding.hide();
					if(typeof upfun=='function'){
						upfun.call(jq,tree);
					}
				}).post(opt.url,opt.args);
			}else if(opt.data){
				tree = $.fn.zTree.init(opt.divs.ztree, opt.setting, opt.data);
			}else{
				tree = $.fn.zTree.init(opt.divs.ztree, opt.setting,[]);
			}
			opt.divs.loadding.hide();

			if(tree&&typeof upfun=='function'){
				upfun.call(jq,tree);
			}
		});
	}
	$.fn.tree = function(){
		if(typeof arguments[0]=='string'){
			return $.fn.tree.methods[arguments[0]].apply(this,Array.prototype.slice.call(arguments,1));
		}
		var opt = $.extend(true,{},$.fn.tree.defaults,arguments[0]);
		opt.treeid = "tree"+Math.ceil(Math.random()*100);
		
		this.empty().css({"height":"100%"});
		var serchbox = $("<input type='text'>");
		initSerchbox.call(this,serchbox,opt);
		serchbox.next().css({"height":"33px","width":"100%","border":"none","border-bottom":"1px solid #D7E3FB"}).find(".textbox-text").css({"width":"150px","height":"36px"}).siblings("span").css({"top":"5px"});
		this.css({"border":"1px solid #D7E3FB", "margin-right":"5px","overflow":"hidden"});
		var divp = $("<div style='position: relative;'></div>").insertAfter(serchbox.next());
		var div = $("<div style='padding: 5px; color: #FFF; font-size: 12px; border-right: 30px solid transparent; border-top: 30px solid #7DD040; width: 50px; margin-top: 3px;'></div>").appendTo(divp);
		$("<span style='top:7px;position: absolute; color: #FFF; padding: 0px 10px; font-size: 12px;'>"+opt.title+"</span>").insertAfter(div);

		$.ajax({
			url:BASEPATH+"/resource/js/component/tree.css",
			success:function(data){
				$("<style>"+data+"</style>").insertAfter(serchbox);
			}
		});
		
		var showRefresh = opt.setting.async.showRefresh==undefined?opt.setting.async.enable:opt.setting.async.showRefresh;
		if(showRefresh){
			$('<span style=" border: none; border-left: 15px solid transparent; position: absolute; top: 0; height: 16px; border-bottom: 15px solid #2DA8EE; left: 72px; z-index: 8; "></span>').insertAfter(div);
			$('<span style=" border: none; border-left: 15px solid transparent; position: absolute; top: 0; height: 14px; border-bottom: 15px solid #FFF; left: 78px; z-index: 9; "></span>').insertAfter(div);
			var span = $('<span id="refreshSpanDiv" style="top:10px;line-height:17px;border-bottom:2px solid #2DA8EE;width: 85px;position: absolute;color: #008AEA;cursor: pointer;right: 10px;padding: 0px 10px;font-size: 12px;text-align: right;" id="refresh"><span>刷新  </span><svg width="15" height="15" viewBox="0 0 200 160" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g><g transform="scale(0.1953125, 0.1953125)"><path d="M883.875 684.806 883.875 684.806c41.592-90.131 47.607-188.11 23.715-277.077-27.468-102.682-95.063-194.238-193.08-249.865l43.48-93.961-247.21 64.819 110.564 230.424 45.491-98.308c66.606 40.672 112.204 104.396 131.498 176.146 17.257 64.639 13.024 134.926-17.145 200.514-38.445 83.352-110.309 140.105-192.603 162.245-11.892 3.177-24.003 5.62-36.221 7.297l51.033 105.49c4.853-1.129 9.665-2.263 14.447-3.572C731.146 878.755 830.987 799.709 883.875 684.806L883.875 684.806zM359.179 767.282c-67.595-40.598-113.886-104.87-133.367-177.273-17.252-64.64-12.985-134.967 17.145-200.48 38.447-83.386 110.31-140.141 192.605-162.28 13.646-3.651 27.541-6.275 41.587-7.957l-50.886-106.037c-6.676 1.426-13.353 2.956-19.957 4.744-113.266 30.272-213.141 109.317-266.07 224.221-41.511 90.097-47.533 188.11-23.639 277.038l0.073 0.293c27.686 103.375 96.083 195.406 195.196 250.886l-41.111 89.661 246.955-65.694L406.381 664.382 359.179 767.282 359.179 767.282zM359.179 767.282" fill="#2DA8EE"></path></g></g></svg></span>').insertAfter(div);
			var spanDisabled = $('<span id="refreshSpanDisabledDiv" style="display:none;top:10px;line-height:17px;border-bottom:2px solid #2DA8EE;width: 85px;position: absolute;color: #b1b7bb;cursor: pointer;right: 10px;padding: 0px 10px;font-size: 12px;text-align: right;" id="refresh"><span>刷新  </span><svg width="15" height="15" viewBox="0 0 200 160" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g><g transform="scale(0.1953125, 0.1953125)"><path d="M883.875 684.806 883.875 684.806c41.592-90.131 47.607-188.11 23.715-277.077-27.468-102.682-95.063-194.238-193.08-249.865l43.48-93.961-247.21 64.819 110.564 230.424 45.491-98.308c66.606 40.672 112.204 104.396 131.498 176.146 17.257 64.639 13.024 134.926-17.145 200.514-38.445 83.352-110.309 140.105-192.603 162.245-11.892 3.177-24.003 5.62-36.221 7.297l51.033 105.49c4.853-1.129 9.665-2.263 14.447-3.572C731.146 878.755 830.987 799.709 883.875 684.806L883.875 684.806zM359.179 767.282c-67.595-40.598-113.886-104.87-133.367-177.273-17.252-64.64-12.985-134.967 17.145-200.48 38.447-83.386 110.31-140.141 192.605-162.28 13.646-3.651 27.541-6.275 41.587-7.957l-50.886-106.037c-6.676 1.426-13.353 2.956-19.957 4.744-113.266 30.272-213.141 109.317-266.07 224.221-41.511 90.097-47.533 188.11-23.639 277.038l0.073 0.293c27.686 103.375 96.083 195.406 195.196 250.886l-41.111 89.661 246.955-65.694L406.381 664.382 359.179 767.282 359.179 767.282zM359.179 767.282" fill="#b1b7bb"></path></g></g></svg></span>').insertAfter(div);
			span.on("click",function(){
				//连续刷新导致ztree数据重复，这里做延时处理，防止连续点击刷新
				$('#refreshSpanDiv').hide();
				$('#refreshSpanDisabledDiv').show();
				setTimeout(function () { 
					$('#refreshSpanDisabledDiv').hide();
					$('#refreshSpanDiv').show();
			    }, 1000);
				$(this).parent().parent().tree("refresh","root");
			});
		}
		var ztree = $("<ul id='"+opt.treeid+"' style='overflow:auto;' class='ztree tree'></ul>")
		initZtree.call(this,ztree,opt);
		var loading = $("<div class='loading'></div>");
		initLoading.call(this,loading,opt);
		var menu = $("<div style='position: fixed;'></div>");
		initMenu.call(this,menu,opt);
		
		load.call(this,opt,opt.onLoad);
		$.data(this[0],"tree",{options:opt});
		this.height(this.parent().height()-10).width(190);
		this.parent().css({"overflow":"hidden"});
		ztree.css({"overflow-x":"hidden"}).height(this.outerHeight()-ztree.offset().top+this.parent().parent().offset().top-10);

		$.onResize = function(_a,_b){
			var jq = $(this).children().height(_b-10);
			var ztree = $.data(this.children[0]).tree.options.divs.ztree;
			ztree.height(jq.outerHeight()-ztree.offset().top+jq.parent().parent().offset().top-9);
		};
		this.parent().attr("data-options",this.parent().attr("data-options")+",onResize:$.onResize");
		try{
			this.parent().panel("resize");
		}catch(e){
		}
		return this;
	}
	$.fn.tree.defaults = {
		searchable:true,
		searchtype:"hidden"||"hightlight",
		divs:{},
		title:"列表",
		checks:[],
		searchopt:{
			width:"180px",
			icons:[{
				iconCls:'icon-search',
				handler: function(e){
				}
			}],
			clearicon:false,
			edit:true,
			iconWidth:'25',
			iconHeight:'24'
		},
		setting:{
			view: { 
				showLine: false, 
				showIcon: false, 
				selectedMulti: false, 
				dblClickExpand: false, 
				fontCss: function getFontCss(treeId, treeNode) {
					return (!!treeNode.highlight) ? {color:"#A60000", "font-weight":"bold","overflow":"hidden",
						"text-overflow":"ellipsis"} : {color:"#333", "font-weight":"normal"};
				},
				addDiyDom:function(treeId, treeNode){
					var aobj = $("#"+treeId).find("a[id='"+treeNode.tId+"_a']");
					var switchobj = $("#"+treeId).find("span[id='"+treeNode.tId+"_switch']");
					switchobj.prependTo(aobj);
					if(treeNode.level==0){
						$('<i class="fa fa-home" aria-hidden="true"></i>').insertAfter(switchobj);
					}else if(treeNode.isparent){
						$('<i class="fa fa-tags" style="color:#03A9F4" aria-hidden="true"></i>').insertAfter(switchobj);
					}else{
						$('<i class="fa fa-tag" style="color:#8BC34A" aria-hidden="true"></i>').insertAfter(switchobj);
					}
					$("<span style='width:"+15*(treeNode.level)+"px;display: inline-block;'></span>").insertBefore(switchobj);
				}
			},
			data: { 
				simpleData: {
					enable: true
				} 
			},
			async: {
				enable: true,
				type: "get",
				autoParam: ["id", "text=type"],
				dataFilter:function(a,c,f){
					return f.data;
				}
			},
			menu:{
				enable:false,
				defaults:{
					/*locker:{
						text: '锁定', 
						id:"locker", 
						iconCls: 'icon-lock', 
			       		click: function(node){ 
			       			var locknode = function(node,upfunc){ 
			       				if(node&&node.children){ 
			       					$.each(node.children,function(i,item){ 
			       						upfunc(item); 
			       						locknode(item,upfunc); 
			       					});
			       				}
			       			} 
			       			if(node.locked){ 
				       			node.locked=false; 
				       			locknode(node,function(n){ 
				       				n.locked = false; 
				       				console.log(n); 
				       			}); 
			       			} else { 
			       				node.locked=true; 
			       				locknode(node,function(n){ 
			       					n.locked = true; 
			       				});
			       			}
			       		}
			       	},*/
			       	separator:{separator: true},
			       	refresh:{
			       		text: '刷新', 
						id:"refresh", 
			       		click: function(node,ztree){
			       			ztree.reAsyncChildNodes(node,'refresh',true);
				       	}
			       	},
			       	showchild:{
			       		text: '展示全部节点',
			       		id:"showchild", 
			       		click: function(node,ztree){
			       			var nodes = ztree.getNodesByParam("isHidden", true,node);
			       			ztree.showNodes(nodes);
			       			ztree.expandNode(node, true, false, true);
			       		}
			       	},
			       	add:{text: '新增', id:"add",click: function(node){ }
			       	}
				},
				items:[ ],
				onClickItem:function(item,node,tree){},
				onClick:function(item,treenode){
					if(!item.disabled){
						var tree = $.fn.zTree.getZTreeObj(this.divs.ztree.attr("id"));
						item.click(treenode,tree);
						this.setting.menu.onClickItem.call(this,item,treenode,tree);
					}
				},
				onShow:function(node){
					if(node.locked){
						this.tree("updateMenuItem","locker",{text:"解锁",iconCls:"icon-unlock"});
					}else{
						this.tree("updateMenuItem","locker",{text:"锁定",iconCls:"icon-lock"});
					}
				}
			},
			callback:{
				onRightClick: function(event, treeId, treeNode) {
					if(!treeNode) return;
					zTree = this.getZTreeObj(treeId);
					var offset = $(event.target).offset();
					if (event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
						zTree.cancelSelectedNode();
						zTree.showMenu({
							top:event.clientY,
							left:event.clientX
						},treeNode);
					} else if (!treeNode.noR) {
						zTree.selectNode(treeNode);
						zTree.showMenu({
							top:event.clientY,
							left:event.clientX
						},treeNode);
					}
				}
			}
		}
	},
	$.fn.tree.methods = {
		options:function(){
			return $.data(this[0],"tree").options;
		},
		menu:function(){
			return this.tree("options").divs.menu;
		},
		searchbox:function(){
			return this.tree("options").divs.searchbox;
		},
		search:function(arg){
			return this.each(function(){
				searchNode(arg,$(this).tree("options"));
			});
		},
		loadding:function(){
			return this.tree("options").divs.loadding;
		},
		tree:function(){
			return $.fn.zTree.getZTreeObj($(this).tree("options").treeid);
		},
		updateNode:function(nodes){
			return this.each(function(){
				var zTree = $.fn.zTree.getZTreeObj($(this).tree("options").treeid);
				if(nodes instanceof Array){
					$.each(nodes,function(i,node){
						zTree.updateNode(node);
					});
				}else zTree.updateNode(nodes);
			})
		},
		lockNode:function(node,islocked,ele){
			return this.each(function(){
				if(islocked==false)
					node.locked=false;
				else
					node.locked=true;
			});
		},
		refresh:function(node){
			return this.each(function(){
				if($(this).tree("tree")){
					if(!node)
						node = $(this).tree("tree").getSelectedNodes();
					if(node=="root"){
						return $(this).tree("tree").reAsyncChildNodes(null,'refresh',null);
					}
					for(var i in node){
						$(this).tree("tree").reAsyncChildNodes(node[i].getParentNode(),'refresh',null);
					}
				}
			});
		},
		updateMenuItem:function(src,target){
			return this.each(function(){
				var menu = $(this).tree("menu");
				if(typeof src == "number"||typeof src=="string"){
					src = menu.menu("findItem",src);
				}else{
					src = menu.menu("findItem",src.text);
				}
				if(!src){return;}
				menu.menu("updateItem",src,target);
			})
		}
	}
});